import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Typography, Row, Col, Statistic, Spin, Empty, message, Modal } from 'antd';
import { EditOutlined, DeleteOutlined, EyeOutlined, ShopOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { ProductCard } from '@/components';
import { productService } from '@/services';
import { Product } from '@/types';
import { useNavigate } from '@umijs/max';

const { Title } = Typography;
const { confirm } = Modal;

const MyProducts: React.FC = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({
    total: 0,
    onSale: 0,
    sold: 0,
    offShelf: 0
  });
  
  const navigate = useNavigate();

  useEffect(() => {
    loadMyProducts();
  }, []);

  const loadMyProducts = async () => {
    try {
      setLoading(true);
      const result = await productService.getMyProducts({
        page: 1,
        pageSize: 50
      });
      
      const myProducts = result.data || [];
      setProducts(myProducts);
      
      // 统计信息
      setStats({
        total: myProducts.length,
        onSale: myProducts.filter(p => p.status === 'available').length,
        sold: myProducts.filter(p => p.status === 'sold').length,
        offShelf: myProducts.filter(p => p.status === 'off_shelf').length
      });
    } catch (error) {
      message.error('加载我的商品失败');
    } finally {
      setLoading(false);
    }
  };

  const handleViewProduct = (product: Product) => {
    navigate(`/products/detail/${product.id}`);
  };

  const handleEditProduct = (product: Product) => {
    navigate(`/products/publish?edit=${product.id}`);
  };

  const handleDeleteProduct = (product: Product) => {
    confirm({
      title: '确认删除商品',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除商品"${product.title}"吗？此操作不可恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await productService.deleteProduct(product.id);
          message.success('商品删除成功');
          loadMyProducts();
        } catch (error) {
          message.error('删除商品失败');
        }
      }
    });
  };

  const handleOffShelf = (product: Product) => {
    confirm({
      title: '确认下架商品',
      icon: <ExclamationCircleOutlined />,
      content: `确定要将商品"${product.title}"下架吗？下架后买家将无法看到此商品。`,
      okText: '确认下架',
      cancelText: '取消',
      onOk: async () => {
        try {
          await productService.updateProduct(product.id, {
            ...product,
            status: 'off_shelf'
          });
          message.success('商品下架成功');
          loadMyProducts();
        } catch (error) {
          message.error('下架商品失败');
        }
      }
    });
  };

  const handlePublishNew = () => {
    navigate('/products/publish');
  };

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* 页面标题 */}
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">我的商品</h1>
        <p className="text-gray-600">管理您发布的所有商品</p>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} className="mb-6">
        <Col xs={24} sm={12} lg={6}>
          <Card className="shadow-sm border-0">
            <Statistic
              title="总商品数"
              value={stats.total}
              prefix={<ShopOutlined className="text-blue-500" />}
              valueStyle={{ color: '#0ea5e9' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card className="shadow-sm border-0">
            <Statistic
              title="在售商品"
              value={stats.onSale}
              prefix={<ShopOutlined className="text-green-500" />}
              valueStyle={{ color: '#22c55e' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card className="shadow-sm border-0">
            <Statistic
              title="已售商品"
              value={stats.sold}
              prefix={<ShopOutlined className="text-orange-500" />}
              valueStyle={{ color: '#f97316' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card className="shadow-sm border-0">
            <Statistic
              title="已下架"
              value={stats.offShelf}
              prefix={<ShopOutlined className="text-gray-500" />}
              valueStyle={{ color: '#6b7280' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 商品列表 */}
      <Card 
        className="shadow-sm border-0"
        title={
          <div className="flex justify-between items-center">
            <span className="text-lg font-semibold text-gray-900">商品列表</span>
            <div className="space-x-2">
              <Button type="primary" className="bg-blue-600 hover:bg-blue-700" onClick={handlePublishNew}>
                发布新商品
              </Button>
            </div>
          </div>
        }
      >
        {loading ? (
          <div className="flex justify-center py-12">
            <Spin size="large" />
          </div>
        ) : products.length === 0 ? (
          <Empty 
            description="您还没有发布任何商品" 
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          >
            <Button type="primary" onClick={handlePublishNew}>
              发布第一个商品
            </Button>
          </Empty>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {products.map((product) => (
              <div key={product.id} className="relative">
                <ProductCard
                  product={product}
                  showFavorite={false}
                  showActions={false}
                  onClick={() => handleViewProduct(product)}
                  size="medium"
                />
                <div className="mt-2 flex justify-end space-x-2">
                  <Button 
                    type="link" 
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={() => handleViewProduct(product)}
                  >
                    查看
                  </Button>
                  <Button 
                    type="link" 
                    size="small"
                    icon={<EditOutlined />}
                    onClick={() => handleEditProduct(product)}
                  >
                    编辑
                  </Button>
                  {product.status === 'available' && (
                    <Button 
                      type="link" 
                      size="small"
                      onClick={() => handleOffShelf(product)}
                    >
                      下架
                    </Button>
                  )}
                  <Button 
                    type="link" 
                    size="small" 
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => handleDeleteProduct(product)}
                  >
                    删除
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
};

export default MyProducts;